package com.lx.huimailf.activity.p_status_act;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.lx.huimailf.R;
import com.lx.huimailf.adapter.PeopleAdapter;
import com.lx.huimailf.configs.Config;
import com.lx.huimailf.fragment.order.GiveProgressFragment;
import com.lx.huimailf.fragment.order.OrderDetialFragment;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;

public class WaitGetGoodsActivity extends FragmentActivity {
	private ViewPager viewPager;
	private RadioGroup radioGroup;
	private ArrayList<Fragment> fs;
	private MyPagerAdapter adapter;
	private RadioButton rb0;
	private RadioButton rb1;
	private TextView pipeiPeople;
	private RelativeLayout fanhui;
	private String custid="";
	private View peopleListView;
	private RecyclerView peoplelistRV;
	private String status="";
	String orderno="";
	AlertDialog dialog = null;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_waitgoods);
		SharedPreferences sp=getSharedPreferences("user", Context.MODE_PRIVATE);
		custid=sp.getString("custid","-1111");
		status=getIntent().getStringExtra("status");
		orderno=getIntent().getStringExtra("orderno");
		fanhui=(RelativeLayout)findViewById(R.id.fanhui);
		pipeiPeople=(TextView)findViewById(R.id.pipei);
		if(status.equals("-1")){
			pipeiPeople.setVisibility(View.VISIBLE);
		}

		pipeiPeople.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				//为了解决AlertDialog 第二次点击报错
				if(peopleListView!=null){
					((ViewGroup) peopleListView.getParent()).removeView(peopleListView);
				}
				peopleListView = LayoutInflater.from(WaitGetGoodsActivity.this).inflate(R.layout.dialog_recyclerview_city, null, false);
				peoplelistRV=(RecyclerView) peopleListView.findViewById(R.id.rv_people);

				final AlertDialog.Builder builder = new AlertDialog.Builder(WaitGetGoodsActivity.this);
				builder .setTitle("请选择配送人")
						.setView(peopleListView);
				dialog=builder.create();
				dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
				Window dialogWindow = dialog.getWindow();
				WindowManager m = getWindowManager();
				Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
				WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
				p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6，根据实际情况调整
				p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.75，根据实际情况调整
				dialogWindow.setAttributes(p);
				dialog.show();
				getPeopleList();
			}
		});
		fanhui.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				WaitGetGoodsActivity.this.finish();

			}
		});
		setViews();
		setAdapter();
		setListener();
	}
	/**
	 * 添加监听
	 */
	@SuppressWarnings("deprecation")
	private void setListener() {
		try {
			viewPager.setOnPageChangeListener(new OnPageChangeListener() {
				public void onPageSelected(int position) {
					switch (position) {
						case 0:
							rb0.setChecked(true);
							break;
						case 1:
							rb1.setChecked(true);
							break;
					}
				}
				public void onPageScrolled(int arg0, float arg1, int arg2) {

				}
				public void onPageScrollStateChanged(int arg0) {

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 设置适配器
	 */

	private void setAdapter() {
		try {
			//声明存放Fragment的List
			fs=new ArrayList<Fragment>();
			//给list添加fragment对象
			fs.add(new OrderDetialFragment());
			fs.add(new GiveProgressFragment());
			//创建MyPagerAdapter 设置viewPager
			adapter=new MyPagerAdapter(getSupportFragmentManager());
			viewPager.setAdapter(adapter);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 组件初始化
	 */
	private void setViews() {
		viewPager=(ViewPager)findViewById(R.id.viewPager);
		radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
		rb0=(RadioButton)findViewById(R.id.radio00);
		rb1=(RadioButton)findViewById(R.id.radio01);
	}

	public void doClick(View view){
		switch (view.getId()) {
			case R.id.radio00:
				viewPager.setCurrentItem(0);
				break;
			case R.id.radio01:
				viewPager.setCurrentItem(1);
				break;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	class MyPagerAdapter extends FragmentPagerAdapter {

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			return fs.get(position);
		}

		@Override
		public int getCount() {
			return fs.size();
		}

	}

	/**
	 * 配送匹配列表
	 */
	private void getPeopleList(){
		HashMap<String,String> map=new HashMap<>();
		map.put("linkerid",custid);
		Gson gson=new Gson();
		String parmas=gson.toJson(map);
		OkHttpUtils
				.post()
				.url(Config.url+"send/searchDistributer.do")
				.addParams("data",parmas)
				.addParams("mobile","true")
				.build()
				.execute(new StringCallback() {
					@Override
					public void onError(Call call, Exception e, int id) {

					}

					@Override
					public void onResponse(String response, int id) {
					//[{"id":106,"name":"pszx1"},{"id":117,"name":"qwqw"},{"id":118,"name":"qwqw"}]

						ArrayList<HashMap<String,String>> mapArrayList=new ArrayList<HashMap<String, String>>();
						JSONArray jsonArray=null;
						JSONObject jsonObject=null;
						try {
							jsonArray=new JSONArray(response);
							for (int i=0;i<jsonArray.length();i++){
								jsonObject=jsonArray.getJSONObject(i);
								HashMap<String,String> map=new HashMap<String, String>();
								map.put("id",jsonObject.getString("id"));
								map.put("name",jsonObject.getString("name"));
								mapArrayList.add(map);
							}

							PeopleAdapter provincesAdapter=new PeopleAdapter(WaitGetGoodsActivity.this,mapArrayList);
							peoplelistRV.setAdapter(provincesAdapter);
							peoplelistRV.setLayoutManager(new LinearLayoutManager(WaitGetGoodsActivity.this));

							provincesAdapter.setOnItemClickLitener(new PeopleAdapter.OnItemClickLitener() {

								@Override
								public void onItemClick(View view, int position, String senderid) {
									getPeople(senderid);
								}

								@Override
								public void onItemLongClick(View view, int position) {

								}
							});

								} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				});
	}

	/**
	 * 配送匹配到配送人
	 */
	private void getPeople(String senderid){
		HashMap<String,String> map=new HashMap<>();
		map.put("orderno",orderno);
		map.put("senderid",senderid);
		Gson gson=new Gson();
		String parmas=gson.toJson(map);
		OkHttpUtils
				.post()
				.url(Config.url+"order/confirmDis.do")
				.addParams("data",parmas)
				.addParams("mobile","true")
				.build()
				.execute(new StringCallback() {
					@Override
					public void onError(Call call, Exception e, int id) {
						Toast.makeText(WaitGetGoodsActivity.this,"服务器连接超时",Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onResponse(String response, int id) {

						if(response.equals("true")){
							dialog.dismiss();
							Toast.makeText(WaitGetGoodsActivity.this,"匹配配送人成功",Toast.LENGTH_SHORT).show();
							finish();
						}else {
							Toast.makeText(WaitGetGoodsActivity.this,"匹配配送人失败",Toast.LENGTH_SHORT).show();
						}

					}
				});
	}
}
